﻿@using FormBuilder.Components.Workflow
@using FormBuilder
@using FormBuilder.Helpers
@using Microsoft.AspNetCore.Http
@using Microsoft.Extensions.Options;
@using SimpleIdServer.IdServer.Options;
@using System.Text.Json
@model SimpleIdServer.IdServer.UI.ViewModels.SidWorkflowViewModel
@inject IOptions<FormBuilderOptions> options
@inject IUriProvider uriProvider
@inject IHttpContextAccessor HttpContextAccessor;

@{
    Layout = "~/Views/Shared/_FormBuilderLayout.cshtml";
    var antiforgeryToken = HttpContextAccessor.HttpContext.Request.Cookies[options.Value.AntiforgeryCookieName];
    Model.AntiforgeryToken.CookieValue = antiforgeryToken;
    var step = Model.Workflow?.Steps?.SingleOrDefault(s => s.Id == Model.CurrentStepId);
    var path = uriProvider.GetActiveLastFormCssUrl(step?.FormRecordCorrelationId);
    var beginRegisterUrl = Model.Input["BeginRegisterUrl"].ToString();
    var registerStatusUrl = Model.Input["RegisterStatusUrl"].ToString();
}

<component type="typeof(WorkflowViewer)"
           render-mode="ServerPrerendered"
           param-Input="@Model.Input"
           param-Workflow="@Model.Workflow"
           param-FormRecords="@Model.FormRecords"
           param-CurrentStepId="@Model.CurrentStepId"
           param-ErrorMessages="@Model.ErrorMessages"
           param-SuccessMessages="@Model.SuccessMessages"
           param-AntiforgeryToken="@Model.AntiforgeryToken"
           param-SupportedLanguageCodes="@Model.SupportedLanguageCodes" />

@section Header {
    <link rel="stylesheet" href="@path" />
}

@section Scripts {
    <script type="text/javascript">
        let csharpReference;

        var init = function() {
            var beginRegisterUrl = "@beginRegisterUrl";
            var registerStatusUrl = "@registerStatusUrl";
            var isCreated = "IsCreated";
            var isInitialized = false;

            var displayError = function(errorJson) {
                csharpReference.invokeMethodAsync("SetErrorMessage", errorJson["error_description"]);
            }

            var displaySuccessMessage = function () {
                csharpReference.invokeMethodAsync("SetSuccessMessage", "User is created");
                csharpReference.invokeMethodAsync("ClearErrorMessages");
                csharpReference.invokeMethodAsync("SetInputData", isCreated, "true");
                $("#generateQrCodeForm").attr("style", "display: none !important");
                $("#qrCodeContainer").attr("style", "display: none !important");
            }

            var displayQRCode = function (img, qrCode) {
                $("#generateQrCodeForm").attr("style", "display: none !important");
                $("#qrCodeContainer").css("display", "");
                $("#qrCodeContainer img").attr("src", img);
            }

            async function checkStatus(sessionId, nextRegistrationRedirectUrl) {
                setTimeout(async function(){
                    let response = await fetch(registerStatusUrl + "/" + sessionId, {
                        method: 'GET'
                    });
                    if (!response.ok) {
                        let responseJson = await response.json();
                        displayError(responseJson);
                        await checkStatus(sessionId, nextRegistrationRedirectUrl);
                        return;
                    }

                    if(nextRegistrationRedirectUrl) {
                        window.location.href = nextRegistrationRedirectUrl;
                    } else {
                        displaySuccessMessage();
                    }
                }, 1000);
            }

            async function makeCredential(login, displayName, form) {
                let response = await fetch(beginRegisterUrl, {
                    method: 'POST',
                    body: JSON.stringify({ login: login, display_name: displayName, credential_type: 'mobile' }),
                    headers: {
                        "Accept": "application/json",
                        "Content-Type": "application/json"
                    }
                });

                if (!response.ok) {
                    let responseJson = await response.json();
                    displayError(responseJson);
                    return;
                }
                
                const sessionId = response.headers.get('SessionId');
                const qrCode = response.headers.get('QRCode');
                let nextRegistrationRedirectUrl = response.headers.get('NextRegistrationRedirectUrl');
                const blob = await response.blob();
                const img = URL.createObjectURL(blob);
                displayQRCode(img, qrCode);
                await checkStatus(sessionId, nextRegistrationRedirectUrl);
            };

            var tryListenForm = function () {
                const elt = $("#generateQrCodeForm");
                if (isInitialized === true) return;
                if (elt.length === 0) {
                    setTimeout(() => tryListenForm(), 500);
                    return;
                }

                isInitialized = true;
                elt.submit(function (e) {
                    e.preventDefault();
                    var login = $("#generateQrCodeForm input[name='Login']").val();
                    var displayName = $("#generateQrCodeForm input[name='DisplayName']").val();
                    makeCredential(login, displayName, convertFormToJSON($(e.target)));
                });
            }

            tryListenForm();
        };                

        setCsharpReference = function (ref) {
            csharpReference = ref;
            init();
        };
    </script>
}